package com.dongdongshop.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.dongdongshop.mapper.address.TbAddressMapper;
import com.dongdongshop.mapper.address.TbAreasMapper;
import com.dongdongshop.mapper.address.TbCitiesMapper;
import com.dongdongshop.mapper.address.TbProvincesMapper;
import com.dongdongshop.pojo.address.TbAddress;
import com.dongdongshop.pojo.address.TbAddressExample;
import com.dongdongshop.pojo.order.TbOrder;
import com.dongdongshop.service.address.AddressService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
@Service
public class AddressServiceImpl implements AddressService {

    @Resource
    private TbAddressMapper tbAddressMapper;
    @Resource
    private TbProvincesMapper provincesMapper;

    @Resource
    private TbCitiesMapper citiesMapper;

    @Resource
    private TbAreasMapper areasMapper;

    @Override
    public TbOrder getReceiver(Long addressId, TbOrder tbOrder) {
        TbAddress address = tbAddressMapper.selectByPrimaryKey(addressId);
        String ProvinceName = provincesMapper.selectByProvincesId(address.getProvinceId());
        String cityName = citiesMapper.selectByCityId(address.getCityId());
        String townName = areasMapper.selectByTownId(address.getTownId());
        String address1 = address.getAddress();
        String receiver = ProvinceName+cityName+townName+address1;
        tbOrder.setReceiverAreaName(receiver);
        tbOrder.setReceiverMobile(address.getMobile());
        tbOrder.setReceiver(address.getContact());
        return tbOrder;
    }

    @Override
    public void addAddress(TbAddress tbAddress) {
        tbAddressMapper.insertSelective(tbAddress);
    }

    @Override
    public void setDefault(Long id) {
        //获取为1的修改为0
        TbAddressExample addressExample=new TbAddressExample();
        TbAddressExample.Criteria criteria = addressExample.createCriteria();
        criteria.andIsDefaultEqualTo("1");
        List<TbAddress> addressList=tbAddressMapper.selectByExample(addressExample);
        for (TbAddress tbAddress : addressList) {
            tbAddress.setIsDefault("0");
            tbAddressMapper.updateByPrimaryKeySelective(tbAddress);
        }
        //修改
        TbAddress tbAddress=new TbAddress();
        tbAddress.setId(id);
        tbAddress.setIsDefault("1");
        tbAddressMapper.updateByPrimaryKeySelective(tbAddress);
    }

    @Override
    public int deleteById(Long id) {
        return tbAddressMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<TbAddress> getAddress(String username) {
        return tbAddressMapper.getAddress(username);
    }
}
